package com.janko.sccommon.util;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;

import java.util.HashMap;
import java.util.Map;

/**
 * HTTP/JSON数据封装
 * @param <T>
 */
public class ResultFormat<T> {

    private Integer code;
    private String message;
    private T data;

    private ResultFormat(Integer code, String message, T data) {
        this.code = code;
        this.message = message;
        this.data = data;
    }

    public static <T> String success(String message, T data) {
        return new ResultFormat(200, message, data).toJSONString();
    }

    public static <T> String success(Integer code, String message, T data) {
        return new ResultFormat(code, message, data).toJSONString();
    }

    public static <T> String success(T data) {
        return new ResultFormat(200, "success!", data).toJSONString();
    }

    public static <T> Map<String, Object> successMap(T data) {
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("code", 200);
        resultMap.put("message", "success");
        resultMap.put("data", data);
        return resultMap;
    }
    public static <T> Map<String, Object> error(T data,String message) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("code", 500);
        resultMap.put("message", message);
        resultMap.put("data", data);
        return resultMap;
    }

    public static <T> Map<String, Object> successMap() {
        return successMap(null);
    }

    public static String error(String message) {
        return new ResultFormat(2, message, "").toJSONString();
    }

    public static String error(Integer code, String message) {
        return new ResultFormat(code, message, "").toJSONString();
    }
    public static String error(String message,Object data) {
        return new ResultFormat(2, message, data).toJSONString();
    }
    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public String toJSONString() {
        return JSONObject.toJSONString(this, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteDateUseDateFormat, SerializerFeature.WriteNullBooleanAsFalse, SerializerFeature.WriteNullListAsEmpty, SerializerFeature.WriteNullNumberAsZero, SerializerFeature.WriteNullStringAsEmpty);
    }
}